/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcPresenter.java
 *   @Date: 19-1-11 下午2:06
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.presenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.app.otc.bean.PayWayBean;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.otc.OtcApi;
import io.bhex.sdk.otc.OtcConstant;
import io.bhex.sdk.otc.OtcOrderApi;
import io.bhex.sdk.otc.OtcPayChannelApi;
import io.bhex.sdk.otc.OtcUserApi;
import io.bhex.sdk.otc.bean.OrderPendingCountResponse;
import io.bhex.sdk.otc.bean.OtcConfigResponse;
import io.bhex.sdk.otc.bean.OtcLastPriceRequestBean;
import io.bhex.sdk.otc.bean.OtcLastPriceResponse;
import io.bhex.sdk.otc.bean.OtcListRequestBean;
import io.bhex.sdk.otc.bean.OtcListResponse;
import io.bhex.sdk.otc.bean.OtcPayChannelListResponse;
import io.bhex.sdk.otc.bean.OtcPaymentChannelBean;
import io.bhex.sdk.otc.bean.OtcUserInfo;

public class OtcPresenter extends BaseFragmentPresenter<OtcPresenter.OtcUI> {
//    private OtcConfigResponse.TokenBean defaultTokenBean;
    private HashMap<String,OtcConfigResponse.TokenBean> tokenMap = new HashMap<>();
    private HashMap<String,PayWayBean> payWayMap = new HashMap<>();
    private HashMap<String,OtcConfigResponse.CurrencyBean> currencyMap = new HashMap<>();
    //支付方式
    private String payWay="";
    //法币id
    private String currencyId="";
    //默认是购买列表
    private boolean isBuyOrSell=true;
    //默认第一页
    private int page =1;
    private int pageSize =OtcConstant.PAGE_LIMIT;
    private OtcConfigResponse.TokenBean currentTokenBean;
    private List<OtcListResponse.OtcItemBean> currentData = new ArrayList<>();
    private Timer timer;
    private TimerTask timerTask;
    //是否完善了Otc用户信息
    private boolean isHasPayway =false;
    private boolean verifyFlag;
    private boolean bindTradePwd;
    private List<OtcConfigResponse.TokenBean> tokenBeanList;
    private List<OtcConfigResponse.CurrencyBean> currencyList;
    private OtcConfigResponse.CurrencyBean selectCurrency;
    private OtcConfigResponse currentOtcConfig;
    private boolean isShowTabs=false;
    private boolean isVisible;

    public void setSelectCurrency(OtcConfigResponse.CurrencyBean currencyBean) {
        selectCurrency = currencyBean;
        if (selectCurrency != null) {
            currencyId = selectCurrency.getCurrencyId();
        }
    }

    public OtcConfigResponse getConfig() {
        return currentOtcConfig;
    }

    public interface OtcUI extends AppUI{
        void showIndexPrice(OtcLastPriceResponse response, OtcConfigResponse.TokenBean tokenBean,String currencyId);

        void showOtcList(List<OtcListResponse.OtcItemBean> items);

        void showTokenInfo(boolean isBuyOrSell, OtcConfigResponse.TokenBean defaultTokenBean);

        void loadMoreComplete();

        void loadMoreFailed();

        void loadEnd();

        void showConfigInfo(OtcConfigResponse response);

        void showOtcUserInfo(OtcUserInfo response);

        void setUserInfoComplete(boolean isCompleteOfUserOtcInfo);

        void hasPendingOrder(boolean hasPendingOrder, int count);

        void showSwitchBlist(List<OtcConfigResponse.TokenBean> tokenBeanList);

        void showTokensTab(List<OtcConfigResponse.TokenBean> tokenBeanList);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, OtcUI ui) {
        super.onUIReady(activity, ui);
        getOtcConfig();
        getPaymentMethodList();
    }

    /**
     * 获取支付方式列表
     */
    public void getPaymentMethodList() {
        if (!UserInfo.isLogin()) {
            return;
        }
        OtcPayChannelApi.getPayChannelList(new SimpleResponseListener<OtcPayChannelListResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcPayChannelListResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    List<OtcPaymentChannelBean> payChannelList = response.getArray();
                    if (payChannelList != null) {
                        if (payChannelList.size()>0) {
                            //根据用户支付通道 大于 > 0
                            isHasPayway = true;
                            getUI().setUserInfoComplete(true);
                            return;
                        }
                    }
                    isHasPayway = false;
                    getUI().setUserInfoComplete(false);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取Otc用户信息
     */
    private void getOtcUserInfo() {
        if (!UserInfo.isLogin()) {
            return;
        }
        OtcUserApi.getOtcUserInfo(new SimpleResponseListener<OtcUserInfo>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcUserInfo response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    getUI().showOtcUserInfo(response);
                    String nickName = response.getNickName();
                    verifyFlag = response.isVerifyFlag();
                    bindTradePwd = response.isBindTradePwd();
                    //TODO 支付方式设置
//                    isCompleteBaseInfo = !TextUtils.isEmpty(nickName) && verifyFlag && bindTradePwd;
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        isVisible = visible;
        if (visible) {
            getOtcUserInfo();
            getPaymentMethodList();
            getOtcPendingOrder();
            startTimer();
        }else{
            stopTimer();
        }
    }


    private void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (currentTokenBean != null) {
                    getLastPrice(currentTokenBean, currencyId);
                    getOtcList(true,false, currentTokenBean,payWay,currencyId);
                    if (!isHasPayway) {
                        getOtcUserInfo();
                        getPaymentMethodList();
                    }
                    getOtcPendingOrder();
                }else{
                    getOtcConfig();
                }
            }
        };
        timer.schedule(timerTask,OtcConstant.TIMER_DELAY,OtcConstant.TIMER_PERIOD);

    }

    /**
     * 待处理订单
     */
    private void getOtcPendingOrder() {
        if (!UserInfo.isLogin()) {
            return;
        }
        OtcOrderApi.getOrderPendingCount(new SimpleResponseListener<OrderPendingCountResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OrderPendingCountResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    if (response.getCount()>0) {
                        getUI().hasPendingOrder(true,response.getCount());
                    }else{
                        getUI().hasPendingOrder(false,response.getCount());
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }


    private void stopTimer() {
        if (timerTask!=null){
            timerTask.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    private void getOtcConfig() {
        OtcApi.getConfig(new SimpleResponseListener<OtcConfigResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcConfigResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    getUI().showConfigInfo(response);
                    handleConfigData(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    private void handleConfigData(OtcConfigResponse otcConfig) {
        currentOtcConfig = otcConfig;
        //支付的法币
        currencyMap.clear();
        currencyList = otcConfig.getCurrency();
        if (currencyList != null&&currencyList.size()>0) {

            for (int i = 0; i < currencyList.size(); i++) {
                OtcConfigResponse.CurrencyBean currencyBean = currencyList.get(i);
                if (currencyBean != null) {
                    String mCurrencyId = currencyBean.getCurrencyId();
                    if (i==0){
                        this.currencyId = mCurrencyId;
                    }
                    currencyMap.put(mCurrencyId,currencyBean);
                }

            }
        }
        //交易币种
        tokenBeanList = otcConfig.getToken();
        tokenMap.clear();
        if (tokenBeanList != null&&tokenBeanList.size()>0) {
            for (OtcConfigResponse.TokenBean tokenBean : tokenBeanList) {
                tokenMap.put(tokenBean.getTokenId(),tokenBean);
            }
            if (!isShowTabs) {
                isShowTabs = true;
                getUI().showTokensTab(tokenBeanList);
            }
        }
        //支付方式
        payWayMap.clear();
        List<Integer> payments = otcConfig.getPayments();
        if (payments != null&&payments.size()>0) {
            for (Integer paymentWayId : payments) {
                PayWayBean payWayBean = new PayWayBean();
                payWayBean.payWayId = paymentWayId.toString();
                if (paymentWayId ==1){
                    payWayBean.payName = getResources().getString(R.string.string_pay_alipay);
                    payWayBean.payWayDrawableRes = R.mipmap.icon_pay_alipay;
                }else if(paymentWayId ==2){
                    payWayBean.payName = getResources().getString(R.string.string_pay_wechat);
                    payWayBean.payWayDrawableRes = R.mipmap.icon_pay_wechat;
                }else{
                    payWayBean.payName = getResources().getString(R.string.string_pay_union);
                    payWayBean.payWayDrawableRes = R.mipmap.icon_pay_union;
                }
                payWayMap.put(payWayBean.payWayId,payWayBean);
            }
        }
        
    }

    private void showSymbolInfo(boolean isBuyOrSell, OtcConfigResponse.TokenBean defaultTokenBean) {
        if (defaultTokenBean != null) {
            getUI().showTokenInfo(isBuyOrSell,defaultTokenBean);
        }
    }

    public void showPSwitchBList() {
        getUI().showSwitchBlist(tokenBeanList);
    }


    public List<OtcConfigResponse.CurrencyBean> getCurrencyList() {
        if (selectCurrency != null&&currencyList!=null) {
            for (OtcConfigResponse.CurrencyBean currencyBean : currencyList) {
                String currencyId = selectCurrency.getCurrencyId();
                if (currencyBean.getCurrencyId().equals(currencyId)) {
                    currencyBean.setLocalSelect(true);
                }else{
                    currencyBean.setLocalSelect(false);
                }
            }
        }
        return currencyList;
    }


    public void loadMore() {
        requestOtcList(true);
    }

    public void requestOtcListBySwitchB(boolean isLoadMore,boolean isBuyOrSell, OtcConfigResponse.TokenBean tokenBean) {
        clearListShow();
        currentTokenBean = tokenBean;
        this.isBuyOrSell = isBuyOrSell;
        showSymbolInfo(isBuyOrSell,tokenBean);
        requestOtcList(isLoadMore);
        getLastPrice(tokenBean, currencyId);

    }

    public void setFilter(String mPayway) {
        clearListShow();
        payWay = mPayway;
        if (selectCurrency != null) {
            currencyId = selectCurrency.getCurrencyId();
        }
        requestOtcList(false);
    }

    public void requestOtcList(boolean isLoadMore) {
        if (!isLoadMore) {
            //刷新
            this.page =1;
            this.pageSize = OtcConstant.PAGE_LIMIT;
            getOtcList(false,false, currentTokenBean,payWay,this.currencyId);
        }else{
            //加载更多
            getOtcList(false,true, currentTokenBean,payWay,this.currencyId);

        }
    }

    private void clearListShow() {
        getUI().showOtcList(null);
    }

    public void getOtcList(final boolean isAutoRefresh, final boolean isLoadMore, OtcConfigResponse.TokenBean tokenBean, String mPayWay, String mCurrencyId) {
        if(tokenBean == null)
            return;
        if(currentTokenBean==null){
            return;
        }
        if (!currentTokenBean.getTokenId().equals(tokenBean.getTokenId())){
            return;
        }
        OtcListRequestBean otcListRequestBean = new OtcListRequestBean();
        otcListRequestBean.token_id = tokenBean.getTokenId();
//        otcListRequestBean.currency_id = symbolBean.getCurrencyId();
        otcListRequestBean.currency_id = mCurrencyId;
        otcListRequestBean.payment = mPayWay;
        otcListRequestBean.side = isBuyOrSell ?1:0;
        otcListRequestBean.page = isAutoRefresh? 1:page;
        otcListRequestBean.size =isAutoRefresh? page*pageSize : pageSize;

        OtcApi.getOtcList(otcListRequestBean,new SimpleResponseListener<OtcListResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                if (!isLoadMore && !isAutoRefresh && isVisible) {
                    getUI().showProgressDialog("","");
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (isLoadMore) {
                    getUI().loadMoreComplete();
                }
                if (!isLoadMore && !isAutoRefresh) {
                    getUI().dismissProgressDialog();
                }
            }

            @Override
            public void onSuccess(OtcListResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    int count = response.getCount();
                    List<OtcListResponse.OtcItemBean> data = response.getItems();
                    if (data != null) {
                        //TODO
                        if (isAutoRefresh){
                            currentData = data;
                            getUI().showOtcList(currentData);

                            if (data.size()< page*OtcConstant.PAGE_LIMIT) {
                                getUI().loadEnd();
                            }else{
                                getUI().loadMoreComplete();
                            }
                        }else{
                            if (data.size()>0) {
                                page ++;
                            }
                            if (isLoadMore) {
                                //下一页
                                currentData.addAll(data);
                            } else {
                                //刷新
                                currentData = data;
                            }

                            getUI().showOtcList(currentData);

                            if (data.size()< pageSize) {
                                getUI().loadEnd();
                            }else{
                                getUI().loadMoreComplete();
                            }
                        }
                    }else{
                        getUI().loadMoreComplete();
                    }
                }else{
                    getUI().loadMoreFailed();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (isLoadMore) {
                    getUI().loadMoreFailed();
                }
            }
        });
    }

    /**
     * 获取最新价-指数价格
     * @param tokenBean
     * @param currencyId
     */
    private void getLastPrice(final OtcConfigResponse.TokenBean tokenBean, final String currencyId) {
        OtcLastPriceRequestBean otcLastPriceRequestBean = new OtcLastPriceRequestBean();
        otcLastPriceRequestBean.token_id = tokenBean.getTokenId();
        otcLastPriceRequestBean.currency_id = currencyId;
        otcLastPriceRequestBean.side = isBuyOrSell ? 1 : 0;
        OtcApi.getLastPrice(otcLastPriceRequestBean,new SimpleResponseListener<OtcLastPriceResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcLastPriceResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    getUI().showIndexPrice(response,tokenBean,currencyId);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }
}
